<?php
set_time_limit(0);
define('NO_AUTO_DISPATCH', true);
$dir = dirname(__FILE__);
require $dir.'/inc.php';
Core::main();
ob_end_clean();

$sleepSeconds = array(
	1	=> 30,
	2	=> 60,
	3	=> 90,
	4	=> 120,
	5	=> 150,
	5	=> 180,
	6	=> 300,
	7	=> 600,
	8	=> 900,
	9	=> 1800,
	10	=> 3600,
);

$sleepTimes = 0;

while(true) {
	
	// 从队列获取一个待处理任务，并将任务从队列
	$value = Cache::lpop('uags-list');
	// 队列中没有待处理的任务，休息一段时间
	if (!$value) {
		$sleepTimes ++;
		if (isset($sleepSeconds[$sleepTimes])) {
			sleep($sleepSeconds[$sleepTimes]);
		} else {
			sleep($sleepSeconds[10]);
		}
	}
	
	$sleepTimes = 0;
	
	$key = 'uags:'.$value;
	
	$status = Cache::get($key);
	if (false !== $status) {// 对应key存在才处理
		if ($status === '1') {
			continue;
		}
		list($uid, $gameId, $serverId) = explode(',', $value);
		$user = User::read($uid, 'username');
		$username = $user['username'];
		$isActive = Game::isRoleExist($username, $serverId);
		// 已激活，进行处理
		if ($isActive) {
			// 更新数据库标志
			$arr = array('status'=>1);
			$mo = new Model('user_active_game_server');
			$data = array(
				'uid'		=> $uid,
				'game_id'	=> $gameId,
				'server_id'	=> $serverId,
			);
			$mo->where($data)->save($arr);
			// 缓存标志已激活
			Cache::set($key, 1, 43200);
			cmd_print("{$username} 已激活.\n");
		} else {
			// 还未已激活，重新进入队列待检测
			Cache::rpush('uags-list', $value);
		}
	}
	
}

echo "\n";
echo microtime(1) - APP_BEGIN_TIME;
